package aidn.animation.controller 
{
	import aidn.animation.events.CustomEvent;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.getTimer;
	
	
	/** @eventType CustomEvent.UPDATE */
	[Event(name="update", type="aidn.animation.events.CustomEvent")]
	
	/**
	 * 時間配列を用いてイベント制御
	 */
	public class TimeManager extends EventDispatcher
	{
		private var _tts :/*Number*/Array = [];
		
		private var _target :DisplayObject;
		
		private var _now       :int;	// 今のカウント
		private var _startTime :uint;
		
		
		public function TimeManager ( target :DisplayObject ) 
		{
			_target = target;
		}
		
		public function start ( ) :void
		{
			_now = 0;
			_startTime = getTimer();
			
			_target.addEventListener(Event.ENTER_FRAME, _enterFrame);
		}
		
		public function stop ( ) :void
		{
			_target.removeEventListener( Event.ENTER_FRAME, _enterFrame );
		}
		
		
		/**
		 * 時間(単位:ms)配列をセットします。
		 * @param	tts
		 */
		public function setTts ( tts :/*Number*/Array ) :void
		{
			_tts = tts;
		}
		/**
		 * 時間(単位:ms)配列を追加します。
		 * @param	tts
		 */
		public function addTts ( tts :/*Number*/Array ) :void
		{
			_tts = _tts.concat( tts );
		}
		
		
		/* ENTER FRAME */
		private function _enterFrame ( evt :Event ) :void 
		{
			_update();
		}
		private function _update ( ) :void
		{
			if ( _now < _tts.length )
			{
				// 時間が上回ったら、生成
				if ( _tts[_now] < getTimer() - _startTime )
				{
					var e :CustomEvent = new CustomEvent(CustomEvent.UPDATE);
					e.position = _now;
					dispatchEvent(e);
					
					_now ++;
				}
			}
			else
			{
				trace(this, "end");
				_target.removeEventListener( Event.ENTER_FRAME, _enterFrame );
			}
		}
		
	}
}